import thenFs from "then-fs" 

// 获取数据 

async function getData() { 

const str = await thenFs.readFile("./data.json", "utf8") 

return JSON.parse(str) 

} 

/* getData().then((res) => { 

// console.log(res) 

}) */ 

// 增加数据 

async function addData(obj) { 

try { 

const str = await thenFs.readFile("./data.json", "utf8") 

const data = JSON.parse(str) 

obj["id"] = data[data.length - 1].id + 1 

data.push(obj) 

thenFs.writeFile("./增删查改json文件.js", data) 

return "添加成功" 

} catch (e) { 

return "添加失败" 

} 

} 

/* 

addData({ 

author: "长1", 

bookname: "呵呵哈哈哈", 

publisher: "长江出版社", 

}).then((res) => { 

console.log(res) 

}) */ 

// 删除数据 

async function deleteData(id) { 

try { 

const str = await thenFs.readFile("./data.json", "utf8") 

let arr = JSON.parse(str) 

const newArr = arr.filter((ele) => { 

return ele["id"] != id 

}) 

thenFs.writeFile("./data.json", JSON.stringify(newArr)) 

return "删除成功" 

} catch (e) { 

return "删除失败" 

} 

} 

// deleteData(6).then((res) => { 

// console.log(res) 

// }) 

// 修改数据 

async function uploadData(obj) { 

try { 

const str = await thenFs.readFile("./data.json", "utf8") 

let arr = JSON.parse(str) 

let index = arr.findIndex((ele) => { 

return ele.id == obj.id 

}) 

if (index != -1) { 

arr.splice(index, 1, obj) 

thenFs.writeFile("./data.json", JSON.stringify(arr)) 

return "修改成功" 

} else { 

return "没有该id" 

} 

} catch (e) { 

return "修改失败" 

} 

} 

/* uploadData({ 

id: 6, 

author: "长1", 

bookname: "呵呵哈哈哈", 

publisher: "长江出版社", 

}).then((res) => { 

console.log(res) 

}) 

*/